package member

import (
    "fmt"
	"dhfshop/utils/response"
	"dhfshop/models/member"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	TM "github.com/solarhell/tt-miniprogram"
)

type TtPhoneController struct {
	base.BaseController
}

/*******************************************************************

*******************************************************************/
func (this *TtPhoneController) GetPhoneInfo() {
	v := struct {
		EncryptedData  string   `form:"encryptedData" valid:"Required"`
		Iv             string   `form:"iv" valid:"Required"`
		OpenId         string   `form:"open_id" valid:"Required"`
	}{} 
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	sessionKey := ""
	if ttMembers, err := member.GetTtMemberByOpenId(v.OpenId); err == nil {
		sessionKey = ttMembers.SessionKey
	}
	if len(sessionKey) < 5 {
		this.ServeError(fmt.Sprintf("session key is invalid, openid:", v.OpenId))
	    return
	}
	/*
	beego.Debug("v.OpenId:", v.OpenId)
	beego.Debug("sessionKey:", sessionKey)
	beego.Debug("v.EncryptedData:", v.EncryptedData)
	beego.Debug("v.Iv:", v.Iv)
	*/
	phoneInfo, err := TM.DecryptPhoneNumber(sessionKey, v.EncryptedData, v.Iv)
	if err != nil {
		//this.Ctx.Output.SetStatus(401)
		this.ServeCodeError("-41003", response.LangConf.Get("-41003").MustString())
		beego.Debug(err.Error())
		return
	}
	this.Data["json"] = map[string]string{
	    "open_id": v.OpenId,
		"phone_number": phoneInfo.PhoneNumber,
		"pure_phone_number": phoneInfo.PurePhoneNumber,
		"country_code": phoneInfo.CountryCode,
	}
	this.ServeJSON()
}
